package com.effective;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.Stack;

public class SingleObject implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	static SingleObject obj = new SingleObject(1);
	static {
		obj.t = 1;
		obj.fact = new NutritionFacts.Builder(240, 8).calories(100).sodium(35).carbohydrate(27).build();
		obj.s =  "abc";
	}
	
	public NutritionFacts fact;
	public Integer t;
	public String s;
	
	private SingleObject(Integer t) {
		if(obj != null) {
			throw new RuntimeException();
		}
	}
	
	public static SingleObject getInstance() {
		return obj;
	}
	
	public static BigInteger safeInstance(BigInteger val) {
		if(val.getClass() != BigInteger.class) {
			return new BigInteger(val.toByteArray());
		}
		return val;
	}

	public static void main(String[] args) throws Exception {
		SingleObject i1 = SingleObject.getInstance();
		SingleObject i2 = SingleObject.getInstance();
		
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(bos);
		oos.writeObject(i1);
		
		ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
		ObjectInputStream ois = new ObjectInputStream(bis);
		
		SingleObject readObject = (SingleObject) ois.readObject();
		bos.close();
		ois.close();
		
		if(i1.fact == readObject.fact) {
			System.out.println("true");
		}else {
			System.out.println("false");
		}
	}
	
	public Object readResolve() {
		return obj;
	}
}
